<template>
    <div class="app-container" id='editSbuject'>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" label-width="100px" size="mini"
        style="width: 800px;margin-left: 20px;">
        <el-form-item label="专题标题" prop="title">
          <el-input v-model="dataForm.title"></el-input>
        </el-form-item>
        <el-form-item label="专题子标题" prop="subtitle">
          <el-input v-model="dataForm.subtitle"></el-input>
        </el-form-item>
        <el-form-item label="专题图片" prop="picUrl">
          <el-upload class="avatar-uploader" :action="uploadPath" :headers="headers" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="dataForm.picUrl" :src="dataForm.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="专题内容" prop="content">
          <editor :init="editorInit" v-model="dataForm.content"></editor>
        </el-form-item>
        <el-form-item label="商品底价" prop="price">
          <el-input v-model="dataForm.price"></el-input>
        </el-form-item>
        <el-form-item label="阅读量" prop="readCount">
          <el-input v-model="dataForm.readCount"></el-input>
        </el-form-item>
        <el-form-item label="专题商品" prop="goods">
          <el-button type="primary" size="mini" style="float: right;margin-bottom: 10px;" @click="handleCreate">创建商品
          </el-button>
          <el-table :data="goodsList" style="width: 100%;" border fit highlight-current-row>
            <el-table-column prop="id" align="center" label="商品ID" sortable width="120">
            </el-table-column>
            <el-table-column prop="picUrl" align="center" label="图片">
              <template slot-scope="scope">
                <img :src="scope.row.picUrl" width="80">
              </template>
            </el-table-column>
            <el-table-column prop="name" align="center" label="商品名称">
            </el-table-column>
            <el-table-column prop="content" align="center" label="商品介绍">
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="200">
              <template slot-scope="scope">
                <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="updateData">确定</el-button>
      </div>
      <el-dialog title="添加商品" :visible.sync="addVisible" width="60%">
        <div class="filter-container">
          <el-input v-model="listQuery.goodsSn" clearable class="filter-item" style="width: 200px;" placeholder="请输入商品编号">
          </el-input>
          <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="请输入商品名称">
          </el-input>
          <el-button type="primary" class="filter-item" icon="el-icon-search" @click="handleFilter">查询</el-button>
        </div>
        <el-table :data="shopList" style="width: 100%;" border fit highlight-current-row @selection-change="handleSelectctionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" align="center" label="商品ID" sortable width="120">
          </el-table-column>
          <el-table-column prop="picUrl" align="center" label="图片">
            <template slot-scope="scope">
              <img :src="scope.row.picUrl" width="80">
            </template>
          </el-table-column>
          <el-table-column prop="name" align="center" label="商品名称">
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
          @pagination="getList"></pagination>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  <script>
    import Pagination from '@/components/Pagination'
    import Editor from '@tinymce/tinymce-vue'
    import {
      updateSubject,
      uploadPath,
      createStorage,
      readSubject
    } from '@/api/activity/subject'
    import {
      listGoods,
    } from '@/api/goods/goods'
    import {
      getToken
    } from '@/utils/auth'
    export default {
      name: 'editSbuject',
      components: {
        Pagination,
        Editor
      },
      computed: {
        headers() {
          return {
            'Shopping-Admin-Token': getToken()
          }
        }
      },
      data() {
        return {
          uploadPath,
          //新增表单数据
          dataForm: {
            id: '',
            title: '',
            subtitle: '',
            picUrl: '',
            content: '',
            price: '',
            readCount: '',
            goods: []
          },
          //专题商品列表信息
          goodsList: [],
          //专题商品添加状态
          addVisible: false,
          //专题商品的查询数据
          listQuery: {
            page: 1,
            limit: 10,
            goodsSn: '',
            name: '',
          },
          //商品列表
          shopList: [],
          //总条数
          total: 0,
          //表格多选数据
          seletedlist: [],
          //校验规则
          rules: {
            title: [{
              required: true,
              message: '专题标题不能为空',
              trigger: 'blur'
            }],
            subtitle: [{
              required: true,
              message: '专题子标题不能为空',
              trigger: 'blur'
            }],
            content: [{
              required: true,
              message: '标题内容不能为空',
              trigger: 'blur'
            }],
            price: [{
              required: true,
              message: '专题底价不能为空',
              trigger: 'blur'
            }],
          },
           //副文本框初始化属性
           editorInit: {
            language: 'zh_CN',
            convert_urls: false,
            height: 500,
            plugins: [
              'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'
            ],
            toolbar: [
              'searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample',
              'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'
            ],
            // 图片上传钩子
            images_upload_handler: function (blobInfo, success, failure) {
              const formData = new FormData()
              formData.append('file', blobInfo.blob())
              createStorage(formData)
                .then(res => {
                  success(res.data.data.url)
                })
                .catch(() => {
                  failure('上传失败，请重新上传')
                })
            }
          },
          //修改专题Id
          id: ''
        }
      },
      created() {
        // 数据初始化
        if(this.$route.query.id == null){
            return;
        }
        this.id = this.$route.query.id;
        this.getData();
      },
      methods: {
        //查询专题详情
        getData(){
            readSubject({id:this.id}).then(res => {
                this.dataForm = res.data.data.topic;
                this.goodsList = res.data.data.goodsList;
            })
        },
        //打开专题商品新增模态框
        handleCreate() {
          this.listQuery = {
            page: 1,
            limit: 10,
            goodsSn: '',
            name: '',
          };
          this.seletedlist = [];
          this.total = 0;
          this.getList();
          this.addVisible = true;
        },
        //获取专题商品列表
        getList() {
          listGoods(this.listQuery).then(res => {
            this.shopList = [];
            this.shopList = res.data.data.list;
            this.total = res.data.data.total;
          })
        },
        //查询列表
        handleFilter() {
          this.listQuery.page = 1;
          this.getList();
        },
        //表格多选监听变化
        handleSelectctionChange(val){
            this.seletedlist = val;
        },
        //确定添加专题商品
        confirmAdd(){
            //在创建商品中所选择的商品
            console.log(this.seletedlist);
            //回显所选择的商品
            console.log(this.goodsList);
            //提交数据所需要传的表格数据
            console.log(this.dataForm.goods);
            const newGoodsIds = [];
            const newGoodsList = [];
            this.seletedlist.forEach(item => {
              const id = item.id;
              let found = false;
              this.dataForm.goods.forEach(goodsIds => {
                if(id === goodsIds){
                  found = true;
                }
              })
              if(!found){
                newGoodsIds.push(id);
                newGoodsList.push(item)
              }
            })
            if(newGoodsIds.length > 0){
              this.dataForm.goods = this.dataForm.goods.concat(newGoodsIds);
              this.goodsList = this.goodsList.concat(newGoodsList);
            }
            this.addVisible = false
        },
        //删除专题商品
        handleDelete(row) {
          for(var i=0;i<this.dataForm.goods.length;i++){
            if(row.id === this.dataForm.goods[i]){
              this.dataForm.goods.splice(i,1);
            }
          }
          for(var i=0;i<this.goodsList.length;i++){
            if(row.id === this.goodsList[i].id){
              this.goodsList.splice(i,1);
            }
          }
        },
        //确定修改专题
        updateData() {
          this.$refs['dataForm'].validate(valid => {
            if (valid) {
              updateSubject(this.dataForm).then(res => {
                this.$router.push({path:'/activity/subject'});
                this.$notify.success({
                  title: '成功',
                  message: '修改成功'
                });
              })
            }
          })
        },
        //取消新增
        handleCancel(){
          this.$router.push({path:'/activity/subject'});
        },
          //图片上传成功后执行的方法
          handleAvatarSuccess(res, file) {
          this.dataForm.picUrl = res.data.url.replace(/localhost/, '192.168.207.2')
        },
        //图片上传成功前执行的方法
        beforeAvatarUpload(file) {
          // const isJPG = file.type === 'image/jpeg'; 
          // const isLt2M = file.size / 1024 / 1024 < 2;
          // if (!isJPG) {
          //   this.$message.error('上传头像图片只能是 JPG 格式!');
          // }
          // if (!isLt2M) {
          //   this.$message.error('上传头像图片大小不能超过 2MB!');
          // }
          // return isJPG && isLt2M;
        },    
      }
    }
  
  </script>
  <style>
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
  
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  
  </style>
  <style scoped>
  </style>
  